package cc.telecomdigital.tdstock.activity.groups.more;

import java.io.IOException;
import java.io.InputStream;

import android.content.Intent;
import android.graphics.Color;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.AsyncTask.Status;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cc.mango.common.HttpUtils;
import cc.mango.common.StringUtils;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.WebViewHelper;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.CONNECT_TYPE;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.INetworkChangeListener;
import cc.telecomdigital.tdstock.Services.LS_ClientParamMemory;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;

public class TrafficActivity extends BaseActivity implements INetworkChangeListener
{

	private String[]			itemNames;
	private int[]				itemIconIds		= new int[] {
			R.drawable.icon_traffic_1, R.drawable.icon_traffic_2,
			R.drawable.icon_traffic_3, R.drawable.icon_traffic_4,
			R.drawable.icon_traffic_5			};

	private LayoutInflater		flater;

	private DownloadDataTask		task;
	private WebView			webView;
	private ListView              _listView;	

	private static final String	TRAFFIC_URL		= "http://%s/iphone/traffic/itf.do?";
	//private static final String	TRAFFIC_AD_SERVICE	= "http://%s/iphone/ad/ad_c01.gif";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.traffic);

		itemNames = this.getResources().getStringArray(R.array.traffic_items);

		flater = this.getLayoutInflater();

		_listView = (ListView) this.findViewById(R.id.list);
		_listView.setDrawingCacheBackgroundColor(Color.WHITE);
		_listView.setAdapter(adapter);
		_listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				// TODO Auto-generated method stub    

				String title = itemNames[position];

				String it = "T" + (position + 1);

				String url = String.format(TRAFFIC_URL,LS_ClientParamMemory.GetWebServerInfo()
						/*((ITDLApplication) getApplicationContext())
								.getWebServer()*/)
						+ "it=" + it;

				//验证
				String account = ((ITDLApplication) getApplicationContext())
						.getSessionAccount();
				String token = ((ITDLApplication) getApplicationContext())
						.getSessionToken();
				String addParam = new StringBuffer("&account=").append(
						account).append("&token=").append(token)
						.toString();
				url += addParam;

				executeDownloadTask(url, title);
			}

		});

		Button _toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);

		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(),
						MoreActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(MoreActivity.class, intent);
				

			}

		});

		//initWebView();
		WebViewHelper.showAd(this, (WebView) findViewById(R.id.webview));

	}

	@Override
	public void onResume()
	{
		super.onResume();
		_listView.invalidateViews();
	}
	
	private class ViewHolder
	{

		private ImageView	itemIcon;

		private TextView	itemName;

	}

	private BaseAdapter	adapter	= new BaseAdapter()
							{

								@Override
								public int getCount()
								{
									// TODO Auto-generated method stub
									return itemNames.length;
								}

								@Override
								public Object getItem(int position)
								{
									// TODO Auto-generated method stub
									return null;
								}

								@Override
								public long getItemId(int position)
								{
									// TODO Auto-generated method stub
									return 0;
								}

								@Override
								public View getView(int position,
										View convertView,
										ViewGroup parent)
								{
									// TODO Auto-generated method stub

									if (convertView == null)
									{

										convertView = flater
												.inflate(
														R.layout.traffic_item,
														null);

										convertView
												.setBackgroundResource(R.drawable.ordinary_item_bg);

										ViewHolder viewHolder = new ViewHolder();

										viewHolder.itemIcon = (ImageView) convertView
												.findViewById(R.id.more_item_icon);

										viewHolder.itemName = (TextView) convertView
												.findViewById(R.id.more_item_text);

										viewHolder.itemIcon
												.setImageResource(itemIconIds[position]);

										viewHolder.itemName
												.setText(itemNames[position]);

										convertView
												.setTag(viewHolder);
									}
									else
									{

										ViewHolder viewHolder = (ViewHolder) convertView
												.getTag();

										viewHolder.itemIcon
												.setImageResource(itemIconIds[position]);

										viewHolder.itemName
												.setText(itemNames[position]);
									}

									if (position == 0)
									{

										convertView
												.setBackgroundResource(R.drawable.first_item_bg);
									}
									else if (position == getCount() - 1)
									{

										convertView
												.setBackgroundResource(R.drawable.last_item_bg);
									}

									return convertView;
								}

							};

	private class DownloadDataTask extends AsyncTask<String, Void, String>
	{

		private String	title;

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

		}

		@Override
		protected String doInBackground(String... params)
		{

			String url = params[0];

			title = params[1];

			InputStream is = null;

			String allContent = null;

			try
			{
				is = HttpUtils.urlToStream(url);
				/*	} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				   try {*///modified by haibo, fix the NullPointerException, 2011-06-20
				allContent = StringUtils.inputStreamToString(is);
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return allContent;
		}

		@Override
		protected void onPostExecute(String allContent)
		{

			String content = getContent(allContent);

			String timestamp = getTimestamp(allContent);

			if (content != null && timestamp != null && title != null)
			{

				forwardToDetailsActivity(title, timestamp + "\n" + content);
			}

		}
	}

	@Override
	protected void onStop()
	{
		// TODO Auto-generated method stub
		super.onStop();

		if (task != null && task.getStatus() != Status.FINISHED)
		{

			task.cancel(true);

			boolean b = task.isCancelled();

			TDStockLog.d(TAG, "====task is cancell=======" + b);
		}
	};

	private void executeDownloadTask(String url, String title)
	{

		if (task != null && task.getStatus() != Status.FINISHED)
		{

			task.cancel(true);

			boolean b = task.isCancelled();

			TDStockLog.d(TAG, "====task is cancell=======" + b);
		}

		task = new DownloadDataTask();

		task.execute(url, title);

	}

	private String getContent(String s)
	{

		if (s == null)
		{

			return null;
		}

		String result = null;

		int startIndex = s.indexOf("<Contents>") + "<Contents>".length();

		if (startIndex < 0)
		{

			return null;
		}

		int endIndex = s.indexOf("</Contents>", startIndex);

		if (endIndex < 0)
		{

			return null;
		}

		result = s.substring(startIndex, endIndex);

		return result;
	}

	private String getTimestamp(String s)
	{

		if (s == null)
		{

			return null;
		}

		String result = null;

		int startIndex = s.indexOf("<Timestamp>") + "<Timestamp>".length();

		if (startIndex < 0)
		{

			return null;
		}

		int endIndex = s.indexOf("</Timestamp>", startIndex);

		if (endIndex < 0)
		{

			return null;
		}

		result = s.substring(startIndex, endIndex);

		if (result != null)
		{

			result = result.replace(" ", "");

			result = result.substring(10, 15);
		}

		return result;
	}

	private void forwardToDetailsActivity(String title, String content)
	{

		Intent intent = new Intent(getApplicationContext(),
				TrafficDetailsActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		intent.putExtra(TrafficDetailsActivity.PARAMS_KEY_TITLE, title);
		intent.putExtra(TrafficDetailsActivity.PARAMS_KEY_CONTENT, content);
		/*View currView = MoreGroup.group.getLocalActivityManager()
				.startActivity(
						TrafficDetailsActivity.class.getSimpleName(),
						intent).getDecorView();
		MoreGroup.group.setContentView(currView);*/
		
		SwitchForwardActivity(TrafficDetailsActivity.class, intent);
		
		

	}

	/*
	  * Animated gifs are not supported on all android phones. Animated gif support was only introduced in 2.2 and then only for high end phones that had the memory and CPU to handle them.
	  *  more reference: http://code.google.com/p/android/issues/detail?id=3422
	  */
//	private void initWebView()
//	{
//		webView = (WebView) findViewById(R.id.webview);
//		if (webView != null)
//		{
//			//webView.setWebViewClient(new WebViewClient());
//			try
//			{
//				webView.getSettings().setJavaScriptEnabled(true);
//				webView.getSettings().setBlockNetworkImage(false);
//				webView.getSettings().setAppCacheEnabled(false);//no cache to save memory
//				/*webView.loadUrl(String.format(TRAFFIC_AD_SERVICE,
//						((ITDLApplication) getApplicationContext())
//								.getWebServer()));*/
//				
//				webView.setWebViewClient( new  WebViewClient() 
//				{
//					
//					@Override
//				    public boolean shouldOverrideUrlLoading(WebView view, String url) 
//					{
//				        view.loadUrl(url);
//				        return true;
//				    }
//
//					@Override
//					public void onReceivedError(WebView view, int errorCode,
//							String description, String failingUrl) {
//						super.onReceivedError(view, errorCode, description, failingUrl);
//						
//					}
//					
//					
//					
//					
//				});
//				
//				
//				  boolean isProduction = ((ITDLApplication)this.getApplication()).getEnvironment() == CommonDefn.Environment.Production;
//				  final String adUrl= isProduction  ?  CommonDefn.URL_PRODUCTION_AD : CommonDefn.URL_DEVELOPMENT_AD ;
//				  final Handler  handler = new Handler();
//				  new Thread() {
//					  public void run() {
//						
//						  if(HttpUtils.isServiceAvailable(adUrl))
//							 {
//							  		handler.post(   new Runnable() {
//							    	 	public void run() {
//							    	 		 webView.loadUrl(adUrl);
//							    	 	}
//							    	 
//							     });
//							 }
//					  }
//				  }.start();
//				
//					
//				
//
//			}
//			catch (Exception e)
//			{
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//
//		}
//	}
	
	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}

	@Override
	public void NetworkChange_Response(CONNECT_TYPE iConnect,
			NetworkInfo iNetInfo) {

		
		if(iNetInfo.isAvailable() || iNetInfo.isConnected()) {
			WebViewHelper.showAd(this, (WebView) findViewById(R.id.webview));
		}
		
	}
	
	
	
	
	

}